// 映射登录人所拥有的所有的路由组件

let firstMenu = null

export function mapMenusToRoutes(userMenus) {
  const routes = []

  // 1.先去加载默认所有的routes
  const allRoutes = []
  // const routeFiles = require.context('../router/main', true, /\.js/)  //true表示递归查找所有的文件  用于webpack
  const routeFiles = import.meta.glob('../router/main/**/*.js', { eager: true })  //true表示递归查找所有的文件   用于vite
  routeFiles.keys().forEach((key) => { //key是 ==>  ./user/user.js   ./car/car.js   
    const route = require('../router/main' + key.split('.')[1]) //相当于拼接完整路由路径   举例 /main/user/user.js
    allRoutes.push(route.default)
  })



  
  // 2.根据菜单获取需要添加的routes
  // userMenus:
  // type === 1 -> children -> type === 1
  // type === 2 -> url -> route
  // _recurseGetRoute  是递归函数  找到最深层
  const _recurseGetRoute = (menus) => {
    for (const menu of menus) {
      if (menu.type === 2) { //只有等于2的时候才是点击时候映射菜单的
        const route = allRoutes.find((route) => route.path === menu.url)
        if (route) routes.push(route)
        if (!firstMenu) {
          firstMenu = menu
        }
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }

  _recurseGetRoute(userMenus)

  return routes
}


export function pathMapBreadcrumbs(userMenus, currentPath) {
  // breadcrumbs  用来获取面包屑的
  const breadcrumbs = []
  pathMapToMenu(userMenus, currentPath, breadcrumbs)
  return breadcrumbs
}

// /main/system/role  -> type === 2 对应menu
export function pathMapToMenu(
  userMenus,
  currentPath,
  breadcrumbs
) {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        breadcrumbs?.push({ name: menu.name })
        breadcrumbs?.push({ name: findMenu.name })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}


export { firstMenu }